package cn.acewill.yxd.yunxundian.ui.sign;

import android.app.Dialog;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.TaskQuestionAdapter;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.model.wentifenxiBean;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;

/**
 * Created by XXX on 2017/6/1.
 */

public class TaskQuestonListActivity extends BaseActivity implements AdapterView.OnItemClickListener,View.OnClickListener{

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private  ArrayList<RMain> rMains;

    private ListView myQuestionList;
    private TaskQuestionAdapter adapter;
    private Dialog dialog;
    private EditText questionDesc;
    private ArrayList<tempLostRR> rrlist;
    private int schid;
    private RelativeLayout loadingview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task_question_list);
        //加入存储中，数据提交完一起关闭
        CacheActivity.addActivity(this);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //数据重新加载
        if (NetWorkStateReceiver.whetherConnectNetWork==1){
            setShowOrHide(1);
            loadData();
        }else{
            setShowOrHide(3);
            BaseActivity.showAnimaDialog(this,"当前无网络连接，请在网络情况下进行操作");
        }
    }
    public void initView(){
        schid=getIntent().getIntExtra("schid",0);
        this.loadingview= (RelativeLayout) findViewById(R.id.loadingRel);
        Toolbar myToolBar = (Toolbar) findViewById(R.id.myToolBar);
        myToolBar.setTitle("");
        myToolBar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(myToolBar);
        myToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        this.myQuestionList= (ListView) findViewById(R.id.myQuestionList);
        TextView lookWenti = (TextView) findViewById(R.id.lookWenti);
        lookWenti.setOnClickListener(this);
        myQuestionList.setAdapter(adapter);
        myQuestionList.setOnItemClickListener(this);
        TextView addResult = (TextView) findViewById(R.id.addResult);
        addResult.setOnClickListener(this);
    }
    //加载数据
    public void loadData(){
        Map<String,String> map=new HashMap<>();
        map.put("task","loadLostItemBySchid");
        map.put("schid",schid+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    setShowOrHide(2);
                    String[] array = result.split("\\|");
                    if (array[0].equals("200")) {
                        Gson gson = new Gson();
                        Type type = new TypeToken<ArrayList<tempLostRR>>() {
                        }.getType();
                        rrlist = gson.fromJson(pubClass.convertToArrayJson(result), type);
                        adapter = new TaskQuestionAdapter(TaskQuestonListActivity.this, rrlist);
                        myQuestionList.setAdapter(adapter);
                    } else {
                        if (array.length == 4) {
                            BaseActivity.showAnimaDialog(TaskQuestonListActivity.this, array[1]);
                        } else {
                            BaseActivity.showAnimaDialog(TaskQuestonListActivity.this, "当前评估表无失分项，不需填写");
                        }
                    }
                }
                @Override
                public void onFailture() {
                    BaseActivity.showAnimaDialog(TaskQuestonListActivity.this, "数据获取失败,请检查网络状态");
                    setShowOrHide(3);
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.lookWenti:
                //查看填写的失分原因
                finish();
                break;
            case R.id.addResult:
                boolean flag=false;
                if(rrlist!=null) {
                    for (int i = 0; i < rrlist.size(); i++) {
                        if (rrlist.get(i).ischeck()) {
                            flag = true;
                            break;
                        }
                    }
                }
                if (flag){
                    showMyDialog();
                }else{
                    BaseActivity.showAnimaDialog(TaskQuestonListActivity.this,"请选择失分项");
                }
                break;
            case R.id.cancel_btn:
                dialog.dismiss();
                break;
            case R.id.btn_sure:
                //拿到text的值
                String text=questionDesc.getText().toString().trim();
                if (text.length()==0){
                    BaseActivity.showAnimaDialog(TaskQuestonListActivity.this,"请输入问题分析");
                }else{
                    try {
                        loadtitle();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    //目标的所选的问题的id
                    String trowids="";
                    //目标的rowId
                    String titlestr="";
                    if (rrlist!=null){

                        for (int k=0;k<rrlist.size();k++){
                            if (rrlist.get(k).ischeck()){
                                String[] name =TaskQuestionAdapter.loaddata(rMains,rrlist.get(k).getRRowId()).split(" ");
                                trowids+=rrlist.get(k).getID()+",";
                                titlestr+=name[0]+",";
                            }
                        }
                    }
                    String thistrod=trowids.substring(0,trowids.length()-1);
                    String thistitle=titlestr.substring(0,titlestr.length()-1);
                    wentifenxiBean bean=new wentifenxiBean();
                    bean.setSchid(schid);
                    bean.setTrowids(thistrod);
                    bean.setTitlestr(thistitle);
                    bean.setCommonstr(text);
                    try {
                        db.saveOrUpdate(bean);
                        db.selector(wentifenxiBean.class).findAll();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    dialog.dismiss();
                    //跳转至浏览页面
                    finish();
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (rrlist.get(position).ischeck()==false){
            rrlist.get(position).setIscheck(true);
        }else {
            rrlist.get(position).setIscheck(false);
        }
        adapter.notifyDataSetChanged();
    }
    public void showMyDialog(){
        dialog=new Dialog(this,R.style.mydialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(R.layout.question_detail_view);
        initDialog();
        dialog.setCanceledOnTouchOutside(true);
//        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
//            @Override
//            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                if (keyCode== KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)
//                    return true;
//                else
//                    return false;
//            }
//        });
        final Window window = dialog.getWindow();
        if (window != null) {
            window.setWindowAnimations(R.style.AnimBottom);
            final WindowManager.LayoutParams lp = window.getAttributes();
            lp.gravity = Gravity.BOTTOM; // 紧贴底部
            lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
            Point size = new Point();
            Display display = getWindowManager().getDefaultDisplay();
            display.getSize(size);
            lp.height = size.y/2 ;
            window.setAttributes(lp);
            dialog.show();
        }
    }

    //绑定dialog控件
    public void initDialog(){
        TextView btn_sure= (TextView) dialog.findViewById(R.id.btn_sure);
        btn_sure.setOnClickListener(this);
        this.questionDesc= (EditText) dialog.findViewById(R.id.questionDesc);
        TextView cancel_btn= (TextView) dialog.findViewById(R.id.cancel_btn);
        cancel_btn.setOnClickListener(this);
    }

    //返回键监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK) {
            if (dialog != null) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                } else {
                    finish();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    public void loadtitle() throws DbException {
        Schedule schedule=db.selector(Schedule.class).where("ID","=",rrlist.get(0).getSchId()).findFirst();
        sType type=db.selector(sType.class).where("ID","=",schedule.getSTypeID()).findFirst();
        rJson rmian=db.selector(rJson.class).where("ID","=",type.getReportId()).findFirst();
        String json=rmian.getjSon();
        Gson gson=new Gson();
        Type typeList = new TypeToken<ArrayList<RMain>>() {
        }.getType();
        rMains= gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
    }
    public void setShowOrHide(int k){
        if (k==1){
            loadingview.setVisibility(View.VISIBLE);
            myQuestionList.setVisibility(View.GONE);
        }
        if (k==2){
            loadingview.setVisibility(View.GONE);
            myQuestionList.setVisibility(View.VISIBLE);
        }
        if (k==3){//无数据,无网络
            loadingview.setVisibility(View.GONE);
        }
    }
}
